iT邦幫忙

2025 iThome 鐵人賽

DAY 8
0
Modern Web

Angular、React、Vue 三框架實戰養成:從零打造高品質前端履歷網站系列 第 8

Day 8 Angular 元件切分 – 把履歷網站拆成模組化架構

  • 分享至 

  • xImage
  •  

今日目標

  • 了解 Angular Component 是什麼
  • 學會用 CLI 建立新的元件
  • 把 Day 6 的 HTML 拆分成多個元件(Header、Hero、About、Skills、Projects、Contact、Footer)
  • app.component.html 中組裝這些元件

基礎概念:什麼是 Angular Component?

  • Angular 的畫面基本單位就是 Component(元件)
  • 每個元件包含三個部分:
    1. .ts → 邏輯程式(控制資料、事件)
    2. .html → 模板(畫面結構)
    3. .scss → 樣式(只作用在這個元件)

👉 這樣每個部分都各自獨立,方便維護。就像樂高積木一樣,網站就是一堆元件拼在一起。


實作:切分元件

1. 決定切分區塊

我們的履歷網站可以拆成這幾個主要元件:

  • header → 網站導覽列(名字、選單、主題切換)
  • hero → 首屏區塊(自我介紹 + 照片)
  • about → 關於我(文字 + 更多介紹按鈕)
  • skills → 技能區(清單 + 篩選)
  • projects → 作品集(卡片清單)
  • contact → 聯絡我(表單 + 其他聯絡方式)
  • footer → 頁尾(版權訊息)

2. 用 CLI 建立元件

在專案目錄輸入:

ng g c components/header
ng g c components/hero
ng g c components/about
ng g c components/skills
ng g c components/projects
ng g c components/contact
ng g c components/footer

這會自動產生像這樣的結構:

src/app/components/
├─ header/
│  ├─ header.component.ts
│  ├─ header.component.html
│  ├─ header.component.scss
│  └─ header.component.spec.ts
├─ hero/
├─ about/
...


3. 把 HTML 貼進各元件

  • header.component.html → 放 <header> 裡的 HTML
  • hero.component.html → 放 Hero 區塊
  • about.component.html → 放 About 區塊
  • 其他同理

範例:header.component.html

<header class="site-header">
  <div class="container">
    <a class="brand" href="#home">Chiayu</a>
    <nav class="site-nav" aria-label="主選單">
      <ul>
        <li><a href="#about">關於我</a></li>
        <li><a href="#skills">技能</a></li>
        <li><a href="#projects">作品</a></li>
        <li><a href="#contact">聯絡</a></li>
      </ul>
    </nav>
    <button id="theme-toggle" type="button" aria-pressed="false">切換主題</button>
  </div>
</header>


4. 在 app.component.html 組裝元件

CLI 幫我們自動註冊了元件,所以可以直接用標籤呼叫:

<app-header></app-header>
<app-hero></app-hero>
<app-about></app-about>
<app-skills></app-skills>
<app-projects></app-projects>
<app-contact></app-contact>
<app-footer></app-footer>

這樣就等於把一個大 HTML 拆成多個「小積木」。


成果

  1. 成功用 Angular CLI 建立了 7 個元件
  2. 每個元件有自己的 HTML / SCSS 檔案
  3. app.component.html 現在非常乾淨,只剩下組裝用的 <app-xxx> 標籤
  4. 網站在瀏覽器打開後,畫面跟 Day 6 一樣,但結構更清楚了

小心踩雷(初學者常見錯誤)

  1. 把 HTML 貼到 index.html
    • ❌ Angular 的 index.html 只有 <app-root>
    • ✅ 要貼的是各元件的 .component.html
  2. 忘了在 app.component.html 使用元件
    • 建立元件後如果沒組裝,畫面上什麼都不會出現。
  3. CSS 沒生效
    • Angular 元件的 .scss 只作用在該元件
    • 如果想全站通用,要放在 styles.scss
  4. 元件名稱不一致
    • 使用時要對應正確的 selector,例如 @Component({ selector: 'app-header' })<app-header></app-header>

下一步(Day 9 預告)

明天我們要開始學 Angular 的資料綁定 (Data Binding)

  • 用插值({{ }})在模板中顯示變數
  • 在 TS 檔裡定義資料,讓 HTML 自動更新
  • 把 Skills 與 Projects 的清單改成「由程式動態產生」而不是硬寫死在 HTML

上一篇
Day 7 Angular 起手式 – 用 Angular CLI 建立專案骨架
下一篇
Day 9 Angular 資料綁定 – 用程式產生 Skills 與 Projects 清單
系列文
Angular、React、Vue 三框架實戰養成:從零打造高品質前端履歷網站24
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言